package edu.buu.refectory.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import edu.buu.refectory.domain.Cart;
import edu.buu.refectory.domain.User;

/**
 * 基本的工具类.
 *
 * @author Henley<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2016-01-18 <br>
 */
public class CommonUtil {

    /** The Constant log. */
    private static final Logger log = Logger.getLogger(CommonUtil.class);

	/**
	 * 获得当前用户.
	 *
	 * @return the current user
	 */
	public static User getCurrentUser(HttpServletRequest request) {
	    HttpSession session = request.getSession();
	    Object ob = session.getAttribute("auth_user");
		User user = (User)ob;
		return user;
	}
	
	/**
	 * 获得当前用户ID.
	 *
	 * @return the current user id
	 */
	public static Integer getCurrentUserId(HttpServletRequest request){
		Integer userId = null;
		try {
            User user = getCurrentUser(request);
            if(user != null){
                userId = user.getuId();
            }
		}catch (Exception e){
            log.error("getCurrentUserId", e);
		}
		return userId;
	}
	
	/**
	 * 获得当前用户工号.
	 *
	 * @return the current username
	 */
	public static String getCurrentUsername(HttpServletRequest request){
		String userName = null;
		User user = getCurrentUser(request);
		if(user != null){
			userName = user.getuName();;
		}
		return userName;
	}
	
	/**
	 * 从request中获得参数Map，并返回可读的Map.
	 *
	 * @param request the request
	 * @return the parameter map
	 */
	public static Map<String, Object> getParameterMap(HttpServletRequest request) {
		// 参数Map
		Map<String, String[]> properties = request.getParameterMap();
		//返回值Map
		Map<String, Object> returnMap = new HashMap<String, Object>();
		Set<String> keySet = properties.keySet();
		for(String key: keySet){
			String[] values = properties.get(key);
			String value = "";
			if(values != null && (values.length==1&&StringUtils.isNotBlank(values[0]))?true:false){
				for(int i=0;i<values.length;i++){
					if(values[i] != null && !"".equals(values[i])){
//							value = new String(values[i].getBytes("ISO-8859-1"),"UTF-8") + ",";
                    	value += values[i] + ",";
                    }
				}
				if(value != null && !"".equals(value)){
					value = value.substring(0, value.length()-1);
				}
				if(key.equals("keywords")){//关键字特殊查询字符转义
				   value =  value.replace("_", "\\_").replace("%", "\\%");
				}
				returnMap.put(key, value);
			}
		}
		return returnMap;
	}
	
	public static String getHttpClientInfo(HttpServletRequest request) {
		String LABEL = "::";
		String SEPERATOR = "\t";
		String REST_URL = "Request URL";
		String REST_METHOD = "Request Method";
		String CLIENT_IP = "Client IP";
		String USER_AGENT = "User Agent";
		String REST_PARAMS = "Request Params";

		String clientIp = null;
		if (request.getRemoteAddr() != null) {
			clientIp = request.getRemoteAddr();
		} else if (request.getRemoteHost() != null) {
			clientIp = request.getRemoteHost();
		} else if (request.getHeader("X-FORWARDED-FOR") != null) {
			clientIp = request.getHeader("X-FORWARDED-FOR");
		}
		String restURL = request.getRequestURL().toString();
		String restMethod = request.getMethod();
		String userAgent = request.getHeader("user-agent");

		StringBuilder sb = new StringBuilder();
		sb.append(REST_URL + LABEL + restURL + SEPERATOR);
		sb.append(REST_METHOD + LABEL + restMethod + SEPERATOR);
		sb.append(CLIENT_IP + LABEL + clientIp + SEPERATOR);
		sb.append(USER_AGENT + LABEL + userAgent + SEPERATOR);
		sb.append(REST_PARAMS + LABEL + CommonUtil.getParameterMap(request) + SEPERATOR);

		return sb.toString();
	}

	/**
	 * @param session
	 * @return
	 */
	public static Cart getCart(HttpSession session) {
		Cart cart = (Cart) session.getAttribute("cart");
		if(cart==null){
			cart = new Cart();
			session.setAttribute("cart", cart);
		}
		return cart;
	}


}
